﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Xml;
using System.Collections;
using TomanuExtensions;

namespace AmiEmuLib.Render.Filter.ShaderFilter
{
    /// <summary>
    /// List of all shader filters.
    /// </summary>
    [DebuggerDisplay("Count = {Count}")]
    public static class Shaders
    {
        /// <summary>
        /// List of shaders.
        /// </summary>
        private static List<Shader> m_list = new List<Shader>();

        /// <summary>
        /// Static constructor.
        /// </summary>
        static Shaders()
        {
            using (var stream = StreamExtensions.FromResource(typeof(Shaders), "Shaders.xml"))
            {
                XmlReaderExtensions.ReadXml(stream, (reader) =>
                {
                    reader.ReadStartElement(typeof(Shaders).Name);

                    while (reader.IsStartElement())
                        m_list.Add(new Shader(reader));

                    m_list.Sort((s1, s2) => s1.Name.CompareTo(s2.Name));

                    reader.ReadEndElement();
                });
            }
        }

        /// <summary>
        /// Save data to xml. Only for development.
        /// </summary>
        public static void Save()
        {
            XmlWriterExtensions.WriteXml("Shaders.xml", (writer) =>
            {
                writer.WriteStartElement(typeof(Shaders).Name);

                foreach (var shader in m_list)
                    shader.WriteXml(writer);

                writer.WriteEndElement();
            });
        }

        /// <summary>
        /// This list should be use in GUI.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<string> GetShadersNames()
        {
            return from shader in m_list
                   where !shader.Include
                   where !shader.Internal
                   select shader.Name;
        }

        /// <summary>
        /// List of shaders.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Shader> List
        {
            get
            {
                return m_list;
            }
        }

        /// <summary>
        /// Get shader by name.
        /// </summary>
        /// <param name="a_name"></param>
        /// <returns></returns>
        public static Shader GetFilter(string a_name)
        {
            return m_list.First(f => f.Name == a_name);
        }
    }
}
